/**
 * <copyright>
 *
 * Copyright (c) 2013 IBM Corporation and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors: 
 *   IBM - Initial API and implementation
 *
 * </copyright>
 *
 * $Id$
 */
package org.eclipse.jet.internal.taglib.utils;

import java.util.Map;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jet.JET2Context;
import org.eclipse.jet.JET2Writer;
import org.eclipse.jet.ProjectClassLoader;
import org.eclipse.jet.internal.taglib.extend.attribute.pareser.CommentParser;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;

public class TagUtil
{

  public static IProject findProject(JET2Context context){
    String templatePath = context.getTemplatePath();
    String findPath = null;
    if(templatePath.startsWith("..")){
      findPath = templatePath.substring(2);
    }
    findPath = templatePath;
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IResource resource = root.findMember(new Path(findPath));
    if(resource != null){
      return resource.getProject();
    }
    return null;
  }

  public static Class<?> getClass(IProject project, String className) throws ClassNotFoundException, JavaModelException{
    IJavaProject javaProject = JavaCore.create(project);
    ProjectClassLoader loader = new ProjectClassLoader(javaProject);
    return loader.loadClass(className);
  }

  public static Map<String, String> getAttributeMap(String attributes){
    Map<String, String> attributeMap = CommentParser.parser(attributes);
    return attributeMap;
  }

  public static String getProjectPath(String templatePath){
    if(templatePath != null && templatePath.startsWith("../")){
      templatePath = templatePath.substring(3);
    }
    return templatePath;
  }

  public static IResource getTemplateResource(String templatePath){
    if(templatePath != null && templatePath.startsWith("../")){
      templatePath = templatePath.substring(3);
    }
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IResource resource = root.findMember(new Path(templatePath));
    if(resource != null && resource.exists()){
      return resource;
    }
    return null;
  }
  
  public static String getJetLocation(String templatePath, Integer line){
    String jetLocation = "(" + templatePath + (line!=null?":"+line:"") + ")";
    return jetLocation;
  }

}
